package com.sam.im.heiqun.uis.fragments;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.activities.NewPasswordActivity;
import com.sam.im.heiqun.uis.activities.SelectRechargeTypeActivity;
import com.sam.im.heiqun.uis.activities.SendRedPacketSelectActivity;
import com.sam.im.heiqun.utils.CashierInputFilter;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.yuyh.library.utils.EventBusType;
import com.sam.im.heiqun.utils.EventBusTypeObject;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.fragments.BaseFragment;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class SendRedPTFragment extends BaseFragment {

    @BindView(R.id.edit_sendMoney)
    EditText sendMoney;
    @BindView(R.id.edit_message)
    EditText edit_message;
    @BindView(R.id.send)
    Button send;
    @BindView(R.id.sum_money)
    TextView sum_money;
//    @BindView(R.id.pre_tv_title)
//    TextView title;
    @BindView(R.id.tv_balance)
    TextView tvBalance ;
    PGService mPgService;
    private Long destid;

    private AlertDialog payDialog;
    private PasswordEditText payPSD;
    private PGService mPGservice;
    private double balance;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_send_ordinary_redpacket;
    }

    @Override
    public void init(Bundle savedInstanceState) {

        try {
            balance = ((SendRedPacketSelectActivity)getActivity()).balance ;
            tvBalance.setText(getActivity().getResources().getString(R.string.yu_e_1)+balance+getActivity().getResources().getString(R.string.yuan));
        }catch (Exception e){
            e.printStackTrace();
        }

        mPgService = PGService.getInstance();
        destid = getActivity().getIntent().getLongExtra("destid", 0);
        initJ();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshMoney(EventBusTypeObject ebto) {

        if (ebto.getType() == EventBusType.REFRESH_TYPE_RED_MONEY){
            try {
                balance = Double.parseDouble(ebto.getUid());
                tvBalance.setText(getActivity().getResources().getString(R.string.yu_e_1)+ebto.getUid()+getActivity().getResources().getString(R.string.yuan));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public void initJ() {
        mPGservice = PGService.getInstance();
        send.setEnabled(false);
//        title.setText(getResources().getString(R.string.send_red_package));
        InputFilter[] filters = {new CashierInputFilter()};//限定输入为金额模式

        sendMoney.setFilters(filters);
        sendMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (null != editable && !"".equals(editable.toString()) && 0 != Double.parseDouble(editable.toString())&&Double.parseDouble(editable.toString())<=200) {
                    if (Double.parseDouble(editable.toString())>balance){
                        send.setEnabled(false);
                        send.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                        send.setText(getActivity().getResources().getString(R.string.yue_nozu));
                        sum_money.setText("￥ 0.00");
                    }else {
                        send.setText(getActivity().getResources().getString(R.string.send_red_package));
                        send.setBackgroundResource(R.drawable.rp_bg_circle_btn_y);
                        sum_money.setText("￥ " + editable.toString());
                        send.setEnabled(true);
                    }
                } else {
                    if (!"".equals(editable.toString())&&Double.parseDouble(editable.toString())>200){
                        send.setText(getActivity().getResources().getString(R.string.one_redpacket_out200));
                    }else {
                        send.setText(getActivity().getResources().getString(R.string.send_red_package));
                    }
                    send.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                    sum_money.setText("￥ 0.00");
                    send.setEnabled(false);
                }
            }
        });
    }

    @OnClick({ R.id.send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send:
                doSend();
                break;
            case R.id.pay_commit:
                String pwd = payPSD.getText().toString().trim();
                if (null == pwd || "".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
                    validatePayPwd(pwd);
                }
                break;
            case R.id.pay_cancel:
                payDialog.dismiss();
                break;
        }
    }

    /**
     * 做发送红包的逻辑操作
     */
    private void doSend() {
        showProgress(null);
        final UserEntivity user = ToolsUtils.getUser();

        if (!ToolsUtils.currentNetState(getActivity())) {
            return;
        }
        String myUserId = ToolsUtils.getMyUserId();
        mPgService.getBalance(myUserId).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
//                Log.e(TAG, "onResultError: 发送个人红包，接收用户余额出错");
            }
            @Override
            public void onNext(String s) {
                hideProgress();
                balance = Double.parseDouble(s);
                tvBalance.setText(getActivity().getResources().getString(R.string.yu_e_1)+s+getActivity().getResources().getString(R.string.yuan));
                Float balance = Float.valueOf(s);
                Float money = Float.valueOf(sendMoney.getText().toString().trim());
                if (money > balance) {
                    Toast.makeText(getActivity(), getString(R.string.balance_lack_please_recharge), Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getActivity(), SelectRechargeTypeActivity.class));
                } else {
                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                        // Toast.makeText(SendOrdinaryRedPacket.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();
                        showSetPSWdialog();
                        return;
                    }
                    showPayDialog();
                }
            }
        });
    }
    private void showSetPSWdialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getActivity().getResources().getString(R.string.tip_psw));
        builder.setMessage(getActivity().getResources().getString(R.string.no_pay_psw));
        builder.setNegativeButton(getActivity().getResources().getString(R.string.now_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton(getActivity().getResources().getString(R.string.now_go), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(getActivity(), NewPasswordActivity.class);
                intent.putExtra("type", getResources().getString(R.string.set_pay_psd));
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    /**
     * 验证支付密码
     *
     * @param pwd
     */
    private void validatePayPwd(String pwd) {
        String payPsd = MD5.MD532(pwd);
        mPGservice.validatePayPwd(payPsd, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showLongToast(getResources().getString(R.string.pay_psd_verify_defeat));
            }
            @Override
            public void onNext(String validateEntivity) {
                String money = sendMoney.getText().toString().trim();
                String liuyan = edit_message.getText().toString().trim();
                if (null == liuyan || "".equals(liuyan)) {
                    liuyan = getResources().getString(R.string.wish_you_good_fortune_and_every_success);
                }
                sendRedPacket("" + destid, money, liuyan);
                payDialog.dismiss();
            }
        });
    }

    /**
     * 发送红包(发送给个人普通红包)
     *
     * @param uId
     * @param money
     * @param liuyan
     */
    public void sendRedPacket(final String uId, final String money, final String liuyan) {
        Log.i("info", "sendRedPacket: ==================liuyan="+liuyan);

        String userId=ToolsUtils.getMyUserId();
        //要传给后台的参数全部封装成json，然后加密传给后台
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("redPacketType", "2");
        json.put("userId", userId);
        json.put("redPacketCount", "1");
        json.put("redPacketContent", liuyan);
        json.put("destId", uId);
        json.put("destType", "1");
        json.put("redPacketAmount", money);
        json.put("command", "");
        json.put("limit", "");
        String content = RequestRSAUtils.setRsaContent(json);
        mPgService.sendRedPacket(content).subscribe(new AbsAPICallback<String>() {
        //mPgService.sendRedPacket("2", ToolsUtils.getMyUserId(), "1", liuyan, uId, "1", money,"").subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(getResources().getString(R.string.send_faild));
            }

            @Override
            public void onNext(String data) {
//                new ToastUtils().showSingleToast(data);
                Intent intent = new Intent();
                intent.putExtra("destid", uId);
                intent.putExtra("money", money);
                intent.putExtra("liuyan", liuyan);
                intent.putExtra("redPacketId", data);
                getActivity().setResult(10, intent);
                getActivity().finish();
            }
        });
    }
    private void showPayDialog() {
        View dialog = LayoutInflater.from(getActivity()).inflate(R.layout.transfer_account_dialog, null);
        payDialog = new AlertDialog.Builder(getActivity()).setView(dialog).create();
        payDialog.show();
        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(this);
        payCommit.setOnClickListener(this);
    }

    private void popupKeyboard(final PasswordEditText editText) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }

}
